import json

from asgiref.sync import sync_to_async
from channels.generic.websocket import AsyncWebsocketConsumer
from app.Cmds import CmdDict
from app.WsCode import EXCEPTION_NOTICE


def exeCmd(cmd_obj, data):
    """
    执行命令

    因为要包装成异步方法，所以提出来，不能放在类中
    """
    return cmd_obj.exe(data)


class AppConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, code):
        pass

    async def receive(self, text_data=None, bytes_data=None):
        text_data_json = json.loads(text_data)

        code = text_data_json.get('code')
        if code:
            cmd_class = CmdDict.get(code)
            if cmd_class:
                # 执行命令,结果发送给客户端
                result = await sync_to_async(exeCmd)(cmd_class(), text_data_json.get('data'))
                await self.send(text_data=json.dumps(result))
            else:
                await self.send(text_data=json.dumps({'code': EXCEPTION_NOTICE, 'data': '未找到命令：' + str(code)}))
        else:
            await self.send(text_data=json.dumps({'code': EXCEPTION_NOTICE, 'data': '非法的协议号：' + str(code)}))
